package com.neulogistics.contrib.warehouse.infrastructure.persistence.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neulogistics.contrib.warehouse.domain.model.aggregate.Inventory;
import com.neulogistics.contrib.warehouse.domain.repository.IInventoryRepository;
import com.neulogistics.contrib.warehouse.infrastructure.persistence.converter.InventoryEntityPOConverter;
import com.neulogistics.contrib.warehouse.infrastructure.persistence.orm.po.InventoryPO;
import com.neulogistics.contrib.warehouse.infrastructure.persistence.orm.service.IInventoryPOService;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

@Repository
public class InventoryRepository implements IInventoryRepository {
    @Resource
    IInventoryPOService inventoryPOService;

    @Override
    public void save(Inventory inventory) {
        inventory.calculateTotalHold();
        InventoryPO inventoryPO = InventoryEntityPOConverter.entityToPO(inventory);
        inventoryPOService.saveOrUpdate(inventoryPO);
        // 在新增的情况下，需要返回生成的主键
        inventory.setInventoryId(inventoryPO.getInventoryId());
    }

    @Override
    public Inventory findById(Integer id) {
        InventoryPO inventoryPO = inventoryPOService.getById(id);
        Inventory inventory = InventoryEntityPOConverter.POToEntity(inventoryPO);
        return inventory;
    }

    @Override
    public void deleteById(Integer id) {
        inventoryPOService.removeById(id);
    }

    @Override
    public Inventory findByWarehouseAndGoods(Integer warehouseId, Integer goodsId) {
        LambdaQueryWrapper<InventoryPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(InventoryPO::getWarehouseId, warehouseId)
                .eq(InventoryPO::getGoodsId, goodsId);
        InventoryPO inventoryPO = inventoryPOService.getOne(queryWrapper);
        Inventory inventory = InventoryEntityPOConverter.POToEntity(inventoryPO);
        return inventory;
    }
}
